<template>
	<component
		:is="FieldItem?.tag"
		v-model="componentVal"
		:size="FieldItem?.attrs.size"
		:min="FieldItem?.attrs.min"
		:max="FieldItem?.attrs.max"
		:disabled="FieldItem?.attrs.disabled"
	>
		<template v-if="FieldItem?.attrs.optionType !== 'button'">
			<component
				:is="FieldItem?.InputType"
				v-for="item in (options as Array<Record<string,never>>)"
				:key="item!.value"
				:label="item.value"
				:border="FieldItem?.attrs.border"
				:size="FieldItem?.attrs.size"
			>
				{{ item.label }}
			</component>
		</template>
		<template v-else>
			<component :is="FieldItem?.InputType + '-button'" v-for="item in options" :key="item.value" :label="item.value">{{ item.label }}</component>
		</template>
	</component>
</template>

<script setup lang="ts">
import { TabFieldType } from '/@/components/Linxyun/custom/DataStructs/commontype';
import Lxy_page_event_remote from '../custom/CustomCommon/lxy_page_event_remote.js';

type modelValType = string | number | any[];

const props = withDefaults(
	defineProps<{
		modelValue: modelValType;
		FieldItem: TabFieldType | null;
		pageData: Record<string, any>;
		inputData: Record<string, any>;
		globalData: Record<string, any>;
	}>(),
	{
		FieldItem: null,
	}
);
const { modelValue, FieldItem } = toRefs(props);
console.log('radioradioradio', FieldItem.value);

const componentVal = ref<modelValType>(FieldItem.value?.tag === 'el-checkbox-group' ? [] : '');
let options = ref<any[]>([]);
const emit = defineEmits(['update:modelValue']);
watch(
	modelValue,
	(newVal) => {
		componentVal.value = newVal;
	},
	{
		immediate: true,
	}
);
watch(componentVal, (newVal) => {
	emit('update:modelValue', newVal);
});

const init = async () => {
	if (!FieldItem.value?.ifStaticOption) {
		const remoteEvent = new Lxy_page_event_remote({ url: FieldItem.value?.dynamicOptions.url, params: FieldItem.value?.dynamicOptions.params });
		remoteEvent.setDataSrc(props.pageData, props.inputData, props.globalData);
		const res = await remoteEvent.callEvent();
		if (res.code === '0000' && res.success && res.Records && res.Records.length) {
			options.value = res.Records.map((m: any) => {
				return { label: m[FieldItem.value!.dynamicOptions.label], value: String(m[FieldItem.value!.dynamicOptions.value]) };
			});
			console.log('optionsoptions', options);
		}
	} else {
		options.value = FieldItem.value?.options.map((m: any) => {
			m.value = String(m.value);
			return m;
		});
	}
};

onBeforeMount(async () => {
	await init();
});
</script>

<style lang="scss" scoped></style>
